package org.jeecg.modules.zcgl.tencent.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.zcgl.tencent.service.IWxTokenService;
import org.jeecg.modules.zcgl.tencent.service.http.HttpService;
import org.jeecg.modules.zcgl.tencent.vo.AccessTokenResponse;
import org.jeecg.modules.zcgl.util.WxWebUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class WxTokenServiceImpl extends AbstractWxService implements IWxTokenService {

    @Value("${weChat.appId}")
    private String appId;
    @Value("${weChat.secret}")
    private String secret;

    private static final String ACCESS_TOKEN = "access_token";

    @Autowired
    private HttpService httpService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String refreshtWxToken(){
        // params
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put(WxWebUrl.UrlParam.APP_ID, appId);
        paramMap.put(WxWebUrl.UrlParam.APP_SECRET, secret);
        AccessTokenResponse response = null;
        try {
            response = httpService.get(this.fmtReqWebsUrl(WxWebUrl.GET_WX_TOKEN, paramMap), AccessTokenResponse.class);
        } catch (Exception e) {
            log.error("getWxToken() exception. ", e);
        }

        String accessToken = null;
        if (response != null && StringUtils.isNotBlank(response.getAccess_token())) {
            accessToken = response.getAccess_token();
            Integer expiresIn = response.getExpires_in();
            redisUtil.set(ACCESS_TOKEN, accessToken, expiresIn-100);
        }
        log.info("getWxToken() end, accessToken={}", accessToken);
        return accessToken;
    }

    @Override
    public String getWxToken() {
        Object token = redisUtil.get(ACCESS_TOKEN);
        if (token != null){
            return token.toString();
        }

        return this.refreshtWxToken();
    }
}
